<template>
  <div class="absolute left-0 right-0 top-0 bottom-0">
    <router-link tag="div" :to="{path: '/search', query: {type: 'goods'}}" class="p-10 p-b-0">
      <VSearch content="搜索商品" />
    </router-link>
    <div class="wrapper flex">
      <div class="goods-list min-w-100 h-full p-v-10">
        <!-- 左侧菜单栏 -->
        <div ref="leftbar" class="list h-full bg-grey o-y-scroll scroll-touch">
          <p
            v-for="(item, index) in types"
            :key="item.id"
            :class="{'active': leftIndex === index}"
            @click="handleLeftbarClick(index)"
            class="p-r-5vw p-15 fs-rem-14px text-content"
          >{{item.name}}</p>
        </div>
      </div>
      <div ref="rightbar" class="h-full p-h-10 flex-1 o-y-scroll scroll-touch p-h-10 p-t-20">
        <!-- 右侧菜单栏 -->
        <div :ref="`rightbar_${index}`" v-for="(item, index) in types" :key="item.id">
          <p class="fs-rem-14px text-content m-l-10">{{item.name}}</p>
          <div class="flex flex-wrap p-v-15">
            <div
              v-for="child in item.children"
              :key="child.id"
              class="w-p-33 text-center m-t-8 m-b-8"
            >
              <router-link
                :to="{path: '/search/goods', query: {typeName: item.name, type: item.type, childName: child.name}}"
              >
                <img
                  class="w-9vw h-9vw fs-rem-12px b-round text-grey"
                  :src="child.pic || require('@/assets/images/merchant.jpg')"
                  :alt="child.name"
                />
                <p class="text-grey fs-rem-12px p-t-5">{{child.name}}</p>
              </router-link>
            </div>
            <div v-if="!item.children.length" class="fs-rem-13px text-grey m-l-20">暂无分类</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import VSearch from '@/components/VSearch'

let leftbar
let rightbar
let rightChildrenHeight
let rightChildrenOffsetHeight = []
let prevScrollTop = 0
let rightScrollTop
let surpassRightItem
let surpassRightItemIndex
export default {
  data () {
    return {
      types: null,
      leftIndex: 0
    }
  },
  components: {
    VSearch
  },
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      await this.getAllType()
      this.$nextTick(this.addEvent)
    },
    handleLeftbarClick (index) {
      this.leftIndex = index
      this.changeRightbarOffsetHeight(index)
    },
    async getAllType () {
      let { zxGdTypeList } = await this.$api.post('/gd/type/query', {})
      this.types = this.formatTypes(zxGdTypeList)
    },
    formatTypes (types) {
      let rootType = types.filter(d => d.parentId === '0')
      rootType.forEach(d => {
        d.children = types.filter(c => c.type === d.type && c.parentId !== '0')
      })
      return rootType
    },
    changeRightbarOffsetHeight (index) {
      rightbar.scrollTo({
        top: rightChildrenOffsetHeight[index],
        behavior: 'smooth'
      })
    },
    scrollFunc (e) {
      rightScrollTop = e.target.scrollTop
      // 获取到目前滚动所在的位置
      surpassRightItem = rightChildrenOffsetHeight.find(d => d > rightScrollTop)
      // 获取在数组中的下标
      surpassRightItemIndex = rightChildrenOffsetHeight.indexOf(surpassRightItem) - 1
      if (surpassRightItemIndex < 0 || surpassRightItemIndex > rightChildrenOffsetHeight.length - 1) return
      // 对比当前组件的leftIndex和超过元素下标, 不一样的时候赋值
      if (rightScrollTop > prevScrollTop) {
        // 向下
        if (this.leftIndex < surpassRightItemIndex && this.leftIndex !== surpassRightItemIndex) {
          this.leftIndex = surpassRightItemIndex
        }
      } else {
        // 向上
        if (this.leftIndex > surpassRightItemIndex && this.leftIndex !== surpassRightItemIndex) {
          this.leftIndex = surpassRightItemIndex
        }
      }
      prevScrollTop = rightScrollTop
    },
    addEvent () {
      leftbar = this.$refs.leftbar
      rightbar = this.$refs.rightbar
      // 右边菜单每个子元素的高度
      rightChildrenHeight = this.types.map((d, i) => {
        return this.$refs[`rightbar_${i}`][0].clientHeight
      })
      // 右边菜单每个子元素距离顶部的高度
      rightChildrenHeight.forEach((item, index) => {
        rightChildrenOffsetHeight.push(item + rightChildrenOffsetHeight[index - 1] || 0)
      })
      rightbar.addEventListener('scroll', this.$throttle(this.scrollFunc, 100))
    },
    removeEvent () {
      rightbar.removeEventListener('scroll', this.scrollFunc)
    }
  },
  watch: {
    leftIndex (cur) {
      leftbar.scrollTo({
        top: (this.leftIndex - Math.floor(this.types.length / 2)) * 50,
        behavior: 'smooth'
      })
    }
  },
  beforeDestroy () {
    this.removeEvent()
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  height: calc(100% - 44px);
}
.list {
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
  .active {
    position: relative;
    color: #fd4f51;
    &:before {
      content: "";
      position: absolute;
      width: 3px;
      height: 15px;
      background: #fd4f51;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}
</style>
